<template lang="pug">
  .bill-table
    Modal(
      width="1060"
      v-model="isShowShangbaoReplaceModal"
      title="商保替换"
      class-name="vertical-center-modal"
    )
      .clearfix.mb-24
        RadioGroup(v-model="differentSecurity" @on-change="securityChange")
          Radio.display-block.mb-5(v-for="(item, index) of commercialArr" :label="item.securityGUID" :key="index") {{item.securityNO}}

      .clearfix.mb-24
        Input(v-model="searchIdCardNo" search placeholder="请输入在保人员的身份证号进行搜索，用空格分开" :disabled="!currentSecurityNO" @on-search="getInCommercial")

      .ivu-transfer-list.w400.custom-transfer.pull-left
        Row.ivu-transfer-list-header
          Col(span="6") 在保人员
          Col(span="13")
            Button(size="small" @click="handlePrev" :disabled="!(transferData.length > 0 && tableComone.pageIndex > 1)") 上页
            span.pl-5.pr-5.font-12.text-gray-9 {{tableComone.pageIndex}}
            Button(size="small" @click="handleNext" :disabled="!(transferData.length > 0 && tableComone.pageIndex < tableComone.totalPages)") 下页
          Col.text-right(span="5") {{selectTransferData.length}}/{{transferData.length}}

        .ivu-transfer-list-body.pt-4.pb-4
          Checkbox(
            v-if="transferData.length"
            :indeterminate="indeterminateTransferData"
            :value="checkAllTransferData"
            @click.prevent.native="handleCheckAllTransferData"
            :disabled="(selectTransferData.length + targetKeys.length) >= selectArr.length"
          ) 全选
          CheckboxGroup(v-model="selectTransferData" @on-change="handleCheckboxChangeTransferData")
            Checkbox.display-block(v-for="(c_item, idx) of transferData" :key="idx" :label="c_item.id" :disabled="(selectTransferData.indexOf(c_item.id) === -1 && (selectTransferData.length + targetKeys.length) >= selectArr.length) ? true : false") {{c_item.name}}

      .w28.pull-left.ml-10.mr-10.pt-75
        //- Button.action-icon.mb-10(icon="ios-arrow-forward" :disabled="!(selectTransferData.length > 0)" @click="handleTransfer(selectTransferData, 'transferData', 'targetKeys')")
        //- Button.action-icon(icon="ios-arrow-back" :disabled="!(selectTargetKeys.length > 0)" @click="handleTransfer(selectTargetKeys, 'targetKeys', 'transferData')")
        Button.action-icon.mb-10(icon="ios-arrow-forward" :disabled="!(selectTransferData.length > 0 && selectArr.length >= (selectTransferData.length + targetKeys.length))" @click="handleTransfer(selectTransferData, 'transferData', 'targetKeys')")
        Button.action-icon(icon="ios-arrow-back" :disabled="!(selectTargetKeys.length > 0)" @click="handleTransfer(selectTargetKeys, 'targetKeys', 'transferData')")

      .ivu-transfer-list.w320.custom-transfer.pull-left.mr-20
        Row.ivu-transfer-list-header
          Col(span="18")
            span.pull-left.mr-10 被替换人员
            Button(size="small" @click="handleShowBatchImportShangbaoReplaceModal" :disabled="!currentSecurityNO || targetKeys.length === selectArr.length") 导入
          Col.text-right(span="6") {{selectTargetKeys.length}}/{{targetKeys.length}}
        .ivu-transfer-list-body.pt-4.pb-4
          Checkbox(
            v-if="targetKeys.length"
            :indeterminate="indeterminateTargetKeys"
            :value="checkAllTargetKeys"
            @click.prevent.native="handleCheckAllTargetKeys"
          ) 全选
          CheckboxGroup(v-model="selectTargetKeys" @on-change="handleCheckboxChangeTargetKeys")
            Checkbox.display-block(v-for="(c_item, idx) of targetKeys" :key="idx" :label="c_item.id") {{c_item.name}}

      .ivu-transfer-list.w240.custom-transfer
        .ivu-transfer-list-header 新增人员
        .ivu-transfer-list-body
          ul.ivu-transfer-list-content
            li.ivu-transfer-list-content-item(v-for="item, index of selectArr" :key="index")
              span.line-h-25 {{item.name}}
              .pull-right
                Icon.action-icon.mr-5(type="ios-arrow-up" @click="handleMoveUp(index)")
                Icon.action-icon(type="ios-arrow-down" @click="handleMoveDown(index)")

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="empCommercialChange" :loading="!isCanSubmit") 确定

    //- 批量导入商保被替换人员
    BatchImportShangbaoReplaceModal(ref="BatchImportShangbaoReplaceModal" @queryArr="queryTargetKeys")
</template>

<script>
// import { shangbaoReplaceThead } from './../EBtableHead.js'
// import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import { Common } from '@/utils/common.js'
import BatchImportShangbaoReplaceModal from './batchImportShangbaoReplaceModal.vue'

export default {
  name: '',

  props: {
    selectedEmployeeArr: {
      type: Array,
      default () {
        return []
      }
    }
  },

  components: {
    BatchImportShangbaoReplaceModal
  },

  data () {
    return {
      isShowShangbaoReplaceModal: false,
      companyId: '',
      companyName: '',
      transferData: [],
      selectTransferData: [],
      targetKeys: [],
      selectTargetKeys: [],
      selectArr: [],
      differentSecurity: '',
      commercialArr: [], // 可选择的商保种类
      currentSecurityNO: null, // 点击选择的保险ID
      searchIdCardNo: '', // 搜索框里的身份证号
      isCanSubmit: true,
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 100, // 当前页面展示条数
        totalPages: 0
      },
      indeterminateTransferData: false,
      checkAllTransferData: false,
      indeterminateTargetKeys: false,
      checkAllTargetKeys: false
    }
  },

  watch: {
  },

  mounted () {
  },

  methods: {
    ok () {
    },

    cancel () {
      this.isShowShangbaoReplaceModal = false
    },

    show (companyId, companyName) {
      this.companyId = companyId
      this.companyName = companyName
      this.searchIdCardNo = '' // 搜索框
      this.transferData = [] // 在保人员
      this.targetKeys = [] // 被替换人员
      this.differentSecurity = '' // 默认单选项赋为空
      this.isShowShangbaoReplaceModal = true
      this.isCanSubmit = true
    },

    // 穿梭框操作
    handleTransfer (arr, currentArr, targetArr) {
      this.indeterminateTransferData = false,
      this.checkAllTransferData = false,
      this.indeterminateTargetKeys = false,
      this.checkAllTargetKeys = false
      
      var tempArr = []
      arr.map(c_item => {
        for (var i = 0; i < this[currentArr].length; i++) {
          if (c_item === this[currentArr][i].id) {
            tempArr.push(this[currentArr][i])
            this[currentArr].splice(i, 1) // 删除当前列表中相应的员工
          }
        }
      })
      this.selectTransferData = []
      this.selectTargetKeys = []
      this[targetArr] = this[targetArr].concat(tempArr) // 所选择的员工加入目标列表
    },

    // 交换数组元素
    swapItems (arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      return arr
    },

    // 上移
    handleMoveUp (index) {
      console.log('上移:', index)
      if (index == 0) {
        return
      }
      this.swapItems(this.selectArr, index, index - 1)
    },

    // 下移
    handleMoveDown (index) {
      console.log('下移: ', index)
      if (index == this.selectArr.length - 1) {
        return
      }
      this.swapItems(this.selectArr, index, index + 1)
    },

    // 选择商保(单选)
    securityChange (securityNO) {
      this.tableComone.pageIndex = 1
      this.currentSecurityNO = securityNO
      this.getInCommercial()
    },

    searchFn (value) {
      console.log('value: ', value)
    },

    // 获取参保人员
    async getInCommercial (securityNO) {
      var params = {
        CompanyId: this.companyId,
        SecurityNO: this.currentSecurityNO,
        IdCardNo: this.searchIdCardNo,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
      }
      let res = await EmployeesApi.getInCommercial(params)
      console.log('获取参保人员: ', res)
      if (res.status === 200 && res.data.success) {
        this.transferData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.totalPages = res.data.totalPages

        // 检查数组里的每条记录，假如已经在“被替换人员”列表里时，不应继续显示在“在保人员”列表里
        var idCardNoArr = []
        this.transferData.map(item => {
          idCardNoArr.push(item.idCardNo)
        })
        console.log('📚 idCardNoArr: ', idCardNoArr)
        var tempIdCardNoArr = []
        this.targetKeys.map(item => {
          if (idCardNoArr.indexOf(item.idCardNo) !== -1) {
            tempIdCardNoArr.push(item.idCardNo)
          }
        })
        console.log('📚 tempIdCardNoArr: ', tempIdCardNoArr)
        this.transferData = this.handleMapTransferData(this.transferData, tempIdCardNoArr)
      } else {
        this.transferData = []
      }
      return this.transferData
    },

    // 确定商保替换
    async empCommercialChange () {
      // var tempOld = this.selectTargetKeys
      var tempOld = this.targetKeys.map(item => {
        return item.id
      })
      var tempNew = this.selectArr.map(item => {
        return item.id
      })
      // console.log('被替换人员：', this.targetKeys)
      // console.log('tempNew：', tempNew)
      if (tempOld.length === 0) {
        this.$Message.warning('请勾选被替换人员')
      } else if (tempOld.length === tempNew.length) {
        this.isCanSubmit = false
        this.isShowShangbaoReplaceModal = false
        var params = {
          NewEmployeeID: tempNew,
          OldEmployeeID: tempOld,
          SecurityGUID: this.differentSecurity
        }
        console.log('确定商保替换params: ', params)
        let res = await EmployeesApi.empCommercialChange(params)
        console.log('确定商保替换res: ', res)
        if (res.status === 200 && res.data.success) {
          this.$Message.success(res.data.message)
          this.$emit('query')
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
          this.isCanSubmit = true
        }
      } else {
        this.$Message.error({
          content: '被替换人员与新增人员数量不符',
          duration: 10,
          closable: true
        })
      }
    },

    // 批量导入-显示弹窗
    handleShowBatchImportShangbaoReplaceModal () {
      this.$refs.BatchImportShangbaoReplaceModal.show()
      this.$refs.BatchImportShangbaoReplaceModal.file = null
      this.$refs.BatchImportShangbaoReplaceModal.errorData.isError = false
      this.$refs.BatchImportShangbaoReplaceModal.currentSecurityNO = this.currentSecurityNO
      this.$refs.BatchImportShangbaoReplaceModal.searchIdCardNo = this.searchIdCardNo
      this.$refs.BatchImportShangbaoReplaceModal.currentCount = this.selectArr.length
    },

    // 导入被替换人员成功后的操作
    queryTargetKeys (arr) {
      // 被替换人员列表显示导入后返回的数组去重
      this.targetKeys = Common.ToHeavy2(this.targetKeys.concat(arr), 'idCardNo')
      // 把去重后的数组的idCardNo放入新数组
      var idCardNoArr = []
      arr.map(item => {
        idCardNoArr.push(item.idCardNo)
      })
      this.transferData = this.handleMapTransferData(this.transferData, idCardNoArr)
    },

    // 遍历在保人员列表
    handleMapTransferData (arr, idCardNoArr) {
      var tempArr = []
      arr.map((item, index) => {
        if (idCardNoArr.indexOf(item.idCardNo) === -1) {
          tempArr.push(item)
        }
      })
      return tempArr
    },

    handleCheckboxChangeTransferData (idArr) {
      console.log('🚩idArr: ', idArr)
      var tempIdArr = []
      if (idArr.length === this.transferData.length) {
        this.indeterminateTransferData = false
        this.checkAllTransferData = true
      } else if (idArr.length > 0) {
        this.indeterminateTransferData = true
        this.checkAllTransferData = false
      } else {
        this.indeterminateTransferData = false
        this.checkAllTransferData = false
      }

      this.transferData.map(item => {
        if (idArr.indexOf(item.id) !== -1) {
          tempIdArr.push(item.id) // code数组
        }
      })

      this.selectTransferData = tempIdArr
    },

    handleCheckboxChangeTargetKeys (idArr) {
      console.log('🚩idArr: ', idArr)
      var tempIdArr = []
      if (idArr.length === this.targetKeys.length) {
        this.indeterminateTargetKeys = false
        this.checkAllTargetKeys = true
      } else if (idArr.length > 0) {
        this.indeterminateTargetKeys = true
        this.checkAllTargetKeys = false
      } else {
        this.indeterminateTargetKeys = false
        this.checkAllTargetKeys = false
      }

      this.targetKeys.map(item => {
        if (idArr.indexOf(item.id) !== -1) {
          tempIdArr.push(item.id) // code数组
        }
      })

      this.selectTargetKeys = tempIdArr
    },

    handlePrev () {
      this.tableComone.pageIndex--
      this.getInCommercial()
    },

    handleNext () {
      this.tableComone.pageIndex++
      this.getInCommercial()
    },

    // 在保人员全选
    handleCheckAllTransferData () {
      if (this.indeterminateTransferData) {
        this.checkAllTransferData = false;
      } else {
        this.checkAllTransferData = !this.checkAllTransferData;
      }
      this.indeterminateTransferData = false;

      var tempIdArr = []
      if (this.checkAllTransferData) {
        tempIdArr = this.transferData.map(item => {
          return item.id
        })
      } else {
        tempIdArr = [];
      }
      this.selectTransferData = tempIdArr
      console.log('❤ this.selectTransferData: ', this.selectTransferData)
    },

    // 被替换人员全选
    handleCheckAllTargetKeys () {
      if (this.indeterminateTargetKeys) {
        this.checkAllTargetKeys = false;
      } else {
        this.checkAllTargetKeys = !this.checkAllTargetKeys;
      }
      this.indeterminateTargetKeys = false;

      var tempIdArr = []
      if (this.checkAllTargetKeys) {
        tempIdArr = this.targetKeys.map(item => {
          return item.id
        })
      } else {
        tempIdArr = [];
      }
      this.selectTargetKeys = tempIdArr
      console.log('❤ this.selectTargetKeys: ', this.selectTargetKeys)
    }
  }
}
</script>

<style lang="less" scope>
.ivu-transfer-list-header{
  height: 42px;
}
.custom-transfer{
  padding-top: 42px;
  height: 250px;
  .ivu-transfer-list-body{
    overflow-y: scroll;
    .ivu-checkbox-wrapper{
      padding: 3px 16px;
      margin: 0;
      clear: both;
      line-height: 25px;
      .ivu-checkbox{
        margin-right: 5px;
      }
    }
  }
  .ivu-transfer-operation{
    .ivu-btn {
      width: 28px;
      height: 25px;
      line-height: 23px;
      text-align: center;
      font-size: 14px;
      padding: 0;
      span{
        display: block;
      }
    }
  }
  .ivu-transfer-list-content-item{
    padding-top: 3px;
    padding-bottom: 3px;
  }
}
.action-icon{
  width: 28px;
  height: 25px;
  line-height: 23px;
  color: #c5c8ce;
  background-color: #f7f7f7;
  border: solid 1px #dcdee2;
  text-align: center;
  font-size: 14px;
  border-radius: 3px;
  transition: all .3s;
  cursor: pointer;
  padding: 0;
  &:hover{
    color: #fff;
    background-color: #2d8cf0;
    border-color: #2d8cf0;
  }
}
</style>
